﻿using System;

using zijian666.Converts.Abstractions;
using zijian666.Converts.Convertor.Base;
using zijian666.Converts.Core;
using zijian666.Converts.Extensions;

namespace zijian666.Converts.Convertor;

/// <summary>
/// <seealso cref="DateTime" /> 转换器
/// </summary>
public class DateTimeConvertor : FromConvertor<DateTime>
                               , IFrom<object, DateTime>
                               , IFrom<DateTimeOffset, DateTime>
                               , IFrom<int, DateTime>
                               , IFrom<long, DateTime>
{
    /// <inheritdoc/>
    public ConvertResult<DateTime> From(IConvertContext context, DateTimeOffset input) => new(input.LocalDateTime);

    /// <inheritdoc/>
    public ConvertResult<DateTime> From(IConvertContext context, object input)
    {
        var r = context.Convert<DateTimeOffset>(input);
        if (r.Success)
        {
            return new(r.Value.LocalDateTime);
        }
        return context.ConvertFail(this, input);
    }


    /// <inheritdoc/>
    public ConvertResult<DateTime> From(IConvertContext context, int input) => new DateTime(1970, 1, 1, 8, 0, 0).AddSeconds(input);

    /// <inheritdoc/>
    public ConvertResult<DateTime> From(IConvertContext context, long input)
    {
        if (input < 9999999999)
        {
            return new DateTime(1970, 1, 1, 8, 0, 0).AddSeconds(input);
        }
        return new DateTime(1970, 1, 1, 8, 0, 0).AddMilliseconds(input);
    }
}
